<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/6/11
 * Time: 14:57
 */

namespace app\controller\admin;
use app\model\admin\Customer AS model;
use app\model\CustomerKeywords AS keywords;

class Customer extends Base
{
    public function list(){
        $where = [];
        $post = input('post.');
        !empty($post['name']) && $where[] = ['name','like','%'.$post['name'].'%'];
        !empty($post['status']) && $where[] = ['status','=',$post['status']];
        !empty($post['mobile']) && $where[] = ['mobile','like','%'.$post['mobile'].'%'];
        $list = model::where($where)
            ->paginate([
                'page' => $this->page,
                'list_rows' => $this->size
            ]);
        $status = (new model())->status_array;
        return $this->view('/admin/customer/list',[
            'status' => $status,
            'get_status' => input('status',1),
            'get_mobile' => input('mobile',''),
            'list' => $list
        ]);
    }

    public function info(){
        $id = input('id');
        $info = model::find($id);
        $keywords = [];
        $status = (new model())->status_array;
        return $this->view('/admin/customer/info',[
            'info' => $info,
            'status' => $status,
            'keywords' => $keywords
        ]);
    }

    public function save(){
        $id = input('id');
        $post = input('post.');
        if (!empty($post['keywords'])){
            $keywords = $post['keywords'];
            $post['keywords'] = implode(',',array_column($keywords,'keyword'));
        }
        if (!empty($id)){
            $find = model::find($id);
            $find->save($post);
        }else{
            $find = model::create($post);
        }
        if (!empty($keywords)){
            $array = [];
            foreach ($keywords AS $key => $value)
                $array[] = array_merge(['customer_id' => $find->id],$value);
            keywords::where('customer_id',$find->id)->delete();
            (new keywords())->insertAll($array);
        }
        return $this->msg($find);
    }

    public function delete($id){
        $ids = input('ids');
        if (!empty($ids)){
            model::where('id','IN',$ids)->delete();
        }else {
            model::find($id)->delete();
        }
        return $this->msg();
    }
}